﻿using B.S.Warehouse.Domain;
using B.S.Warehouse.ErrorCord;
using B.S.Warehouse.Read.Api.Application.Command.WarehouseManagementCommand;
using MediatR;
using SqlSugar;

namespace B.S.Warehouse.Read.Api.Application.Handelr.WarehouseManagementCommandHandler
{
    public class GetWareHouseCommandHandler : IRequestHandler<GetWareHouseCommand, ApiResult<ApiPaging<WareHouse>>>
    {
        private readonly ISqlSugarClient db;

        public GetWareHouseCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<ApiResult<ApiPaging<WareHouse>>> Handle(GetWareHouseCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<WareHouse>> result = new ApiResult<ApiPaging<WareHouse>>();
            result.Code = ApiEnum.显示成功;
            result.MAG = "查询显示成功";
            var list = db.Queryable<WareHouse>();


            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.WareHouseID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            if (!string.IsNullOrEmpty(request.WareHouseName))
            {
                list = list.Where(p => p.WareHouseName == request.WareHouseName);
            }
            if (!string.IsNullOrEmpty(request.WareHouseNumber))
            {
                list = list.Where(p => p.WareHouseNumber == request.WareHouseNumber);
            }
            if (!string.IsNullOrEmpty(request.Category))
            {
                list = list.Where(p => p.Category == request.Category);
            }

            ApiPaging<WareHouse> paging = new ApiPaging<WareHouse>();
            paging.totalCount = TotalCount;
            paging.PageCount = TotalPage;
            paging.Result = list.ToList();

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
